<template>
  <layout-body>
    <!-- 筛选 -->
    <search-form-main count="4">
      <template #searchForm>
        <el-form :model="searchForm" ref="searchFormRef">
          <div class="search-form">
            <el-form-item
              class="search-form-item"
              prop="goods_name"
              label="商品名称"
            >
              <el-input
                class="ml5"
                v-model="searchForm.goods_name"
                placeholder=""
              /> </el-form-item
            ><el-form-item
              class="search-form-item"
              label="商品分类"
              prop="cate_id"
            >
              <el-cascader
                v-model="searchForm.cate_id"
                :options="goodsCategroySelect"
                :props="{
                  checkStrictly: true,
                  value: 'id',
                  label: 'cate_name',
                  emitPath: false,
                }"
                clearable
                class="form-select-fil"
              />
            </el-form-item>
          </div>
        </el-form>
      </template>
      <template #searchBtn>
        <el-button
          type="primary"
          @click="createClick()"
          v-permission="'store-goods-create'"
          size="default"
        >
          添加商品
        </el-button>
        <el-button text plain bg> 入库 </el-button>

        <el-button text plain bg @click="resetSearch(searchFormRef)"
          >重置筛选</el-button
        >
      </template>
    </search-form-main>
  </layout-body>

  <layout-body-tabs
    class="mt20"
    :tabs="headTab"
    v-model="tabStatus"
    @change="changeTab"
  >
    <!-- 列表 -->
    <el-table :data="lists" row-key="id" v-loading="initLoading" @sort-change="sortChange">
      <el-table-column type="expand">
        <template #default="scope">
          <div class="p20">
            <el-row :gutter="10">
              <el-col :span="12">
                <div>
                  <span>商品分类：</span>
                  <template
                    v-for="(item, index) in scope.row.cate"
                    :key="index"
                  >
                    <span>{{ item.cate_name }}、</span>
                  </template>
                </div>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品图"
        prop="goods_imgs"
        width="100px"
        align="center"
      >
        <template #default="scope">
          <template v-if="scope.row.goods_imgs">
            <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.goods_imgs[0]"
              fit="fill"
            />
          </template>
          <span v-else class="text-grey">无</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="goods_name">
        <template #default="scope">
          <span>{{ scope.row.goods_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销量" sortable prop="sales_actual" align="center">
        <template #default="scope">
          <span>{{ scope.row.sales_actual }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" align="center">
        <template #default="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="goods_status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.goods_status.value"
            size="small"
            :active-value="1"
            :inactive-value="0"
            :loading="scope.row.loading"
            :before-change="
              () => {
                return (scope.row.switch = true);
              }
            "
            @change="statusChange($event, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_time">
        <template #default="scope">
          <span class="text-grey fz12">{{ scope.row.create_time }}</span>
        </template></el-table-column
      >
      <el-table-column align="left" label="操作" width="200">
        <template #default="scope">
          <div class="flex items-center">
            <el-button
              link
              type="primary"
              @click="createClick(scope.row.id)"
              v-permission="'store-goods-update'"
              >编辑</el-button
            >
            <!-- 回收站 -->
            <template v-if="tabStatus == 2">
              <el-dropdown>
                <el-button link class="ml10" type="primary">更多</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="destroy(scope.row.id)"
                      >永久删除</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template v-else>
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="不用了"
                icon="WarningFilled"
                icon-color="red"
                title="确定删除吗？"
                @confirm="del(scope.row.id)"
              >
                <template #reference>
                  <el-button
                    link
                    v-permission="'store-goods-delete'"
                    type="primary"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="flex end">
      <page :listPage="listPage" @change="pageChange"></page>
    </div>
  </layout-body-tabs>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, onMounted, watch } from "vue";
import { enumType, listPageType, Result, ResultError } from "@/types";
import router from "@/router";
import { getGoodsList, delGoods, destroyGoods,updateStatusGoods } from "@/api/store/goods";
import { getGoodsCateList } from "@/api/store/goods_cate";
import { useConfig } from "@/store";
import type { FormInstance } from "element-plus";
const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const configStore = useConfig();

const createClick = (id: number | string = "") => {
  router.push({
    path: "/store/goods/create",
    query: id ? { id } : {},
  });
};

const searchForm = ref<any>({
  goods_name: "",
  cate_id: null,
});

const searchFormRef = ref<typeof FormInstance>();

const resetSearch = (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const headTab = ref<enumType>([
  {
    name: "销售中",
    value: 1,
  },
  {
    name: "仓库中",
    value: 2,
  },
  {
    name: "已售罄",
    value: 3,
  },
  {
    name: "库存预警",
    value: 4,
  },
  {
    name: "回收站",
    value: 5,
  },
]);

const tabStatus = ref<number | string>(1);

const goodsCategroySelect = ref<any>([]);

const changeTab = (val: number | string, tab: any) => {
  tabStatus.value = val;
  toInit(true);
};


const sortChange = (res:any) => {
  console.log(res.order)
  console.log(res.prop)
}

const initLoading = ref<boolean>(true);

const lists = ref<any>([]);

const listPage = ref<listPageType>({
  total: 0,
  limit: configStore.getPageLimit,
  page: 1,
});

// 初始化
const toInit = (initPage:boolean = false) => {
  if(initPage){
    listPage.value.page = 1;
  }
  let obj: any = {},
    search = searchForm.value;
  obj.status = tabStatus.value;
  obj.page = listPage.value.page;
  obj.limit = listPage.value.limit;

  initLoading.value = true;
  getGoodsList(Object.assign(search, obj))
    .then((res: Result) => {
      lists.value = res.data.data;
      listPage.value.total = res.data.total;
      initLoading.value = false;
    })
    .catch((err: ResultError) => {
      initLoading.value = false;
      $utils.errorMsg(err);
    });
};

const pageChange = (res: listPageType) => {
  listPage.value = res;
  toInit();
};

const del = (id: number) => {
  delGoods({
    id,
  })
    .then((res: Result) => {
      toInit();
      $utils.successMsg(res.message);
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const destroy = (id: number) => {
  destroyGoods({
    id,
  })
    .then((res: Result) => {
      toInit();
      $utils.successMsg(res.message);
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const toInitGoodsCategroy = () => {
  getGoodsCateList({})
    .then((res: Result) => {
      goodsCategroySelect.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const statusChange = (
  val: number,
  row: {
    switch: boolean;
    loading: boolean;
    id: number;
  }
) => {
  if (row.switch === true) {
    row.loading = true;
    updateStatusGoods({
      id: row.id,
      status: val,
    })
      .then((res: Result) => {
        row.loading = false;
        toInit();
        $utils.successMsg(res);
      })
      .catch((err: ResultError) => {
        row.loading = false;
        toInit();
        $utils.errorMsg(err);
      });
  }
};


onMounted(() => {
  toInitGoodsCategroy();
  toInit();
});
</script>